const config = require('configModule');
const libs = require('libs');
require('lessDir/base.less');
require('vendorDir/promise.min');
require('bootstrap/dropdown.js');
$(() => {
  if (!IS_PRODUCTION) {
    console.log('如果你看到这个Log，那么这个版本实际上是开发用的版本');
    console.log('API_ROOT:' + config.API_ROOT);
    console.log('PAGE_ROOT:' + config.PAGE_ROOT);
  }
});
function add_zero(m) {
  return m < 10 ? '0' + m : m;
};

function time_WEEK(time_num, sec = false) {
  let show_day = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  let time = new Date(time_num);
  let year = time.getFullYear();
  let month = time.getMonth() + 1;
  let date = time.getDate();
  let day = time.getDay();
  let hour = time.getHours();
  let minute = time.getMinutes();
  if (sec) {
    let seconds = time.getSeconds();
    return year + '年' + add_zero(month) + '月' + add_zero(date) + '号(' + show_day[day - 1] + ') ' + add_zero(hour) + ':' + add_zero(minute) + ':' + add_zero(seconds);
  } else {
    return year + '年' + add_zero(month) + '月' + add_zero(date) + '号(' + show_day[day - 1] + ') ' + add_zero(hour) + ':' + add_zero(minute);
  }
}

function time_CN(time_num, sec = false) {
  let time = new Date(time_num);
  let year = time.getFullYear();
  let month = time.getMonth() + 1;
  let date = time.getDate();
  let hour = time.getHours();
  let minute = time.getMinutes();
  if (sec) {
    let seconds = time.getSeconds();
    return year + '年' + add_zero(month) + '月' + add_zero(date) + '号 ' + add_zero(hour) + ':' + add_zero(minute) + ':' + add_zero(seconds);
  } else {
    return year + '年' + add_zero(month) + '月' + add_zero(date) + '号 ' + add_zero(hour) + ':' + add_zero(minute);
  }
}

function time_EN(time_num, sec = false) {
  let time = new Date(time_num);
  let year = time.getFullYear();
  let month = time.getMonth() + 1;
  let date = time.getDate();
  let hour = time.getHours();
  let minute = time.getMinutes();
  if (sec) {
    let seconds = time.getSeconds();
    return year + '/' + add_zero(month) + '/' + add_zero(date) + ' ' + add_zero(hour) + ':' + add_zero(minute) + ':' + add_zero(seconds);
  } else {
    return year + '/' + add_zero(month) + '/' + add_zero(date) + ' ' + add_zero(hour) + ':' + add_zero(minute);
  }
}
let moduleExports = {
  API_ROOT: config.API_ROOT,
  PAGE_ROOT: config.PAGE_ROOT,
  initPage: function() {
    // body...
    if (moduleExports.checkToken()) {
      vm.hasToken = true;
      moduleExports.ajaxUrl({
        controller: 'user',
        cmd: 'com.rel.porg.pb.user_get_org_list_req',
        async: false,
        success: function(res) {
          vm.org_list = res.orgs;
          let orgid = libs.receiveParamBetweenPages('common', 'orgid', true);
          for (let i in res.orgs) {
            if (res.orgs[i].id === Number(orgid)) {
              vm.current_org = res.orgs[i];
            }
          }
        },
      });
      moduleExports.ajaxUrl({
        controller: 'user',
        cmd: 'com.rel.porg.pb.user_info_req',
        async: false,
        checkUser: true,
        data: {
          req: 2,
        },
        success: res => {
          vm.userinfo = {
            name: res.info.name,
            head: res.info.head,
          };
        },
      });
    }
  },
  ajaxUrl: function(opt) {
    // body...
    let updata = {};
    if (opt.async !== false) {
      opt.async = true;
    };
    if (opt.checkUser !== false) {
      if (opt.data === undefined) {
        opt.data = {
          token: '',
        };
      }
      if (moduleExports.checkToken()) {
        opt.data.token = moduleExports.getCookie('token');
      };
    }
    updata.data = JSON.stringify(opt.data);
    updata.cmd = opt.cmd;
    $.ajax({
      url: config.API_ROOT + opt.controller,
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(updata),
      async: opt.async,
      timeout: 3000,
      headers: {
        'Msg-Type': 'json',
        'Content-Type': 'application/json',
        'token': moduleExports.getCookie('token'),
      },
      beforeSend: function(XMLHttpRequest) {
      },
      success: function(res) {
        // console.log(res);
        if (res.ret === 1) {
          opt.success(res);
        } else if (res.ret === -10000) {
          moduleExports.clearCookie('token', moduleExports.getCookie('token'));
          window.location.href = moduleExports.PAGE_ROOT + 'member/login/page.html';
        } else {
          if (opt.fail !== undefined) {
            opt.fail(res);
          }
        };
      },
      error: function(xhr, textStatus, errorThrown) {
        console.log('error:' + textStatus);
      },
    });
  },
  ajaxContract: (opt) => {
    let updata = {};
    if (opt.async !== false) {
      opt.async = true;
    };
    if (opt.cache !== false) {
      opt.cache = true;
    };
    if (opt.checkUser !== false) {
      if (opt.data === undefined) {
        opt.data = {
          token: '',
        };
      }
      if (moduleExports.checkToken()) {
        opt.data.token = moduleExports.getCookie('token');
      };
    }
    updata.data = JSON.stringify(opt.data);
    updata.cmd = opt.cmd;
    $.ajax({
      url: config.API_ROOT + opt.controller,
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(updata),
      async: opt.async,
      cache: opt.cache,
      headers: {
        'Msg-Type': 'json',
        'Content-Type': 'application/json',
        'token': moduleExports.getCookie('token'),
      },
      success: function(data, textStatus, jqXHR) {
        // console.log(res);
        opt.success(data, textStatus, jqXHR);
      },
      error: function(data) {
        opt.error(data);
      },
    });
  },
  layer: (fn) => {
    require.ensure(['layer/layer.js'], function() {
      // body...
      let layer = require('layer/layer.js');
      fn(layer);
    }, 'ensure/layer');
  },
  layerCloseAll: (index) => {
    require.ensure(['layer/layer.js'], function() {
      // body...
      let layer = require('layer/layer.js');
      if (index) {
        layer.close(index);
      } else {
        layer.closeAll();
      }
    }, 'ensure/layer');
  },
  layerMsg: function(opt) {
    require.ensure(['layer/layer.js'], function() {
      // body...
      let layer = require('layer/layer.js');
      if (opt.msg) {
        layer.msg(opt.msg, {time: opt.time});
      } else {
        layer.msg(opt);
      }
    }, 'ensure/layer_msg');
  },
  layerPage: function(opt) {
    require.ensure(['layer/layer.js'], function() {
      // body...
      let layer = require('layer/layer.js');
      if (!opt.area) {
        opt.area = [];
      }
      layer.open({
        title: opt.title,
        type: 1,
        btn: 0,
        area: opt.area,
        skin: 'layer-org-skin',
        scrollbar: false,
        content: opt.content,
        success: function(layero, index) {
          if (opt.success) {
            opt.success(layero, index);
          }
          avalon.scan(document.querySelector('.m-pop'));
        },
        cancel: (index) => {
          if (opt.cancel) {
            opt.cancel();
          }
          layer.close(index);
        },
      });
    }, 'ensure/layer_page');
  },
  layerConfirm: (opt) => {
    require.ensure(['layer/layer.js'], function() {
      // body...
      let layer = require('layer/layer.js');
      if (!opt.area) {
        opt.area = ['458px'];
      }
      if (!opt.btn) {
        opt.btn = ['确认', '取消'];
      }
      layer.confirm(opt.msg, {
        btn: opt.btn,
        resize: false,
        title: '提示',
        area: ['458px'],
        closeBtn: false,
        skin: 'layer-org-confirm-skin',
      }, function(index) {
        opt.yes(index, layer);
      }, function(index) {
        if (opt.cancel) {
          opt.cancel();
        }
        layer.close(index);
      });
    }, 'ensure/layer_confirm');
  },
  formatTime: (time, type, seconds) => {
    if (type === 'en') {
      return time_EN(time, seconds);
    } else {
      return time_CN(time, seconds);
    }
  },
  formatDate: (stime, etime) => {
    let start = time_WEEK(stime);
    let s_year, s_month, s_day, e_year, e_month, e_day, endtime;
    if (etime) {
      let end = time_CN(etime);
      s_year = start.substring(0, 4);
      e_year = end.substring(0, 4);
      if (s_year === e_year) {
        s_month = start.substring(5, 7);
        e_month = end.substring(5, 7);
        if (s_month === e_month) {
          s_day = start.substring(8, 10);
          e_day = end.substring(8, 10);
          if (s_day === e_day) {
            endtime = end.substring(11, end.length);
          } else {
            endtime = end.substring(8, end.length);
          }
        } else {
          endtime = end.substring(5, end.length);
        }
      } else {
        endtime = end;
      }
      start = start.substring(5, start.length);
      return start + ' 至 ' + endtime;
    } else {
      return start;
    }
  },
  setCookie: function(c_name, value, expiredays, path = '/') {
    let exdate = new Date();
    exdate.setHours(exdate.getHours() + expiredays);
    document.cookie = c_name + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString()) + ';path=' + path;
  },
  clearCookie: function(c_name, value, expiredays = -1, path = '/') {
    let exdate = new Date();
    exdate.setHours(expiredays);
    document.cookie = c_name + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString()) + ';path=' + path;
  },
  getCookie: function(c_name) {
    if (document.cookie.length > 0) {
      let c_start = document.cookie.indexOf(c_name + '=');
      if (c_start !== -1) {
        c_start = c_start + c_name.length + 1;
        let c_end = document.cookie.indexOf(';', c_start);
        if (c_end === -1) c_end = document.cookie.length;
        return unescape(document.cookie.substring(c_start, c_end));
      }
    }
    return '';
  },
  checkToken: () => {
    if (moduleExports.getCookie('token') === '' || moduleExports.getCookie('token') === 'undefined') {
      switch (config.PROJECT_ROOT) {
        case 'porg':
          vm.pop_login();
          break;
        default:
          if (window.location.pathname === config.PAGE_ROOT + 'member/register/page.html' || window.location.pathname === config.PAGE_ROOT + 'member/password_retrieval/page.html') {
          } else {
            if (window.location.pathname !== config.PAGE_ROOT + 'member/login/page.html') {
              window.location.href = config.PAGE_ROOT + 'porg/index/index/page.html';
            }
          }
      }
    } else {
      return true;
    }
  },
  booleanToken: function() {
    if (moduleExports.getCookie('token') === '' || moduleExports.getCookie('token') === 'undefined') {
      return false;
    } else {
      return true;
    }
  },
};
const MENU = {
  porg: [
    {
      title: '组织主页',
      page: 'index/index',
      project: 'porg',
    },
    {
      title: '成员管理',
      page: 'index/index',
      project: 'org',
    },
    {
      title: '权限管理',
      page: 'index/power',
      project: 'org',
    },
    {
      title: '组织资料',
      page: 'member/usercenter',
      project: 'org',
    },
  ],
  org: [
    {
      title: '组织主页',
      page: 'index/index',
      project: 'porg',
    },
    {
      title: '成员管理',
      page: 'index/index',
      project: 'org',
    },
    {
      title: '权限管理',
      page: 'index/power',
      project: 'org',
    },
    {
      title: '组织资料',
      page: 'member/usercenter',
      project: 'org',
    },
  ],
  act: [
    {
      title: '活动管理',
      page: 'index/index',
      project: 'act',
    },
    {
      title: '报名签到',
      page: 'index/sign_in',
      project: 'act',
    },
    {
      title: '票务订单',
      page: 'index/order',
      project: 'act',
    },
  ],
  cms: [
    {
      title: '公告管理',
      page: 'index/index',
      project: 'cms',
    },
    {
      title: '评论管理',
      page: 'index/comment',
      project: 'cms',
    },
  ],
  shop: [
    {
      title: '店铺管理',
      page: 'index/index',
      project: 'shop',
    },
    {
      title: '商品管理',
      page: 'index/index',
      project: 'shop',
    },
    {
      title: '订单管理',
      page: 'index/order',
      project: 'shop',
    },
  ],
};
let vm = avalon.define({
  $id: 'mc_user_info',
  show_org_list: false,
  currentPage: config.PROJECT_ROOT,
  arr_menu: Object.assign(MENU[config.PROJECT_ROOT]),
  org_list: {},
  userinfo: {
    name: '',
    head: '',
  },
  current_org: {
    title: '获取失败',
    logo: 'http://op4axvn75.bkt.clouddn.com/photo_company.png',
  },
  pop_login: (type = 0) => {
    if (!moduleExports.booleanToken()) {
      moduleExports.layer(layer => {
        let page_pop = require('./_login/page.js');
        layer.open({
          title: false,
          type: 1,
          btn: 0,
          area: ['496px', '604px'],
          scrollbar: false,
          content: page_pop.content,
          closeBtn: false,
          success: function() {
            avalon.scan(document.querySelector('.m-pop'));
            if (type !== 0) {
              avalon.vmodels.mc_loginpop.register = 2;
            } else {
              avalon.vmodels.mc_loginpop.login_opt = 1;
            }
          },
        });
      });
    }
  }, // 用于PORG项目登陆弹窗事件
  panelshow: 1, // 用于显示userpanel的tabs切换
  search_key: '',
  getUrl: (project) => {
    if (moduleExports.booleanToken()) {
      return '/' + project + '/index/index/page.html';
    } else {
      return false;
    }
  },
  getBtnTxt: (type) => {
    let data = {
      porg: {
        href: 'javascript: void(0);',
        text: '黑板报',
      },
      org: {
        href: 'javascript: void(0);',
        text: '发任务',
      },
      cms: {
        href: '/cms/index/index/page.html#/article/newArticle',
        text: '发公告',
      },
      act: {
        href: '/act/index/index/page.html#/new/edit',
        text: '发活动',
      },
      shop: {
        href: 'javascript: void(0);',
        text: '上架票务',
      },
    };
    return data[config.PROJECT_ROOT][type];
  },
  getMenuCurrent: el => {
    if (window.location.pathname === '/' + el.project + '/' + el.page + '/page.html') {
      return 'current';
    } else {
      return '';
    }
  },
  bindSearch: () => {
    // 用于PORG项目搜索事件
  },
  booleanToken: () => {
    return moduleExports.booleanToken();
  },
  fn: el => {
    return el.id !== Number(libs.receiveParamBetweenPages('common', 'orgid', true));
  },
  bindPopUsercenterPanel: () => {
    moduleExports.layer(layer => {
      layer.open({
        type: 1,
        shade: [0.01, '#fff'],
        shadeClose: true,
        closeBtn: false,
        title: false,
        area: ['414px', '590px'],
        offset: ['65px', '-230px'],
        fixed: false,
        content: $('.m-pop-usercenter-panel'),
      });
    });
  },
  bindChooseOrg: function(org_id) {
    moduleExports.ajaxUrl({
      controller: 'account',
      cmd: 'com.rel.porg.pb.acc_switch_org_req',
      data: {
        orgid: org_id,
      },
      success: function(res) {
        moduleExports.setCookie('token', res.token, 12);
        libs.sendParamBetweenPages('common', 'orgid', org_id);
        window.location.href = config.PAGE_ROOT + 'index/index/page.html';
      },
    });
  },
  bindExit: function() {
    moduleExports.clearCookie('token', moduleExports.getCookie('token'));
    libs.receiveParamBetweenPages('common', 'orgid');
    libs.receiveParamBetweenPages('common', 'username');
    libs.receiveParamBetweenPages('common', 'userhead');
    window.location.href = '/porg/index/index/page.html';
  },
});
moduleExports.vm_user_info = vm;
module.exports = moduleExports;
